package com.ct.application.shipping.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ct.application.commons.vo.StatusRequest;
import com.ct.application.shipping.model.po.ChuanYuanKuSavePO;
import com.ct.application.shipping.model.po.ChuanYuanKuSearchPO;
import com.ct.application.shipping.model.vo.ChuanYuanKuVO;
import com.ct.application.shipping.service.ChuanYuanKuService;
import com.ct.application.sysuser.model.vo.SysUserDetailVO;
import com.ct.application.sysuser.service.ISystemUserService;
import com.ct.repository.commons.BaseServiceImpl;
import com.ct.shipping.mapper.ChuanYuanKuMapper;
import com.ct.shipping.orm.ChuanBoXinXiDO;
import com.ct.shipping.orm.ChuanYuanKuDO;
import com.ct.shipping.orm.ChuanYuanKuDO;
import com.ct.shipping.orm.SysParameterDO;
import com.ct.utils.result.StatusEnums;
import com.ct.utils.threadlocal.UserThreadLocal;
import com.ct.utils.valid.ValidatorUtil;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 船员库 服务实现类
 * </p>
 *
 * @author carlo
 */
@Service
public class ChuanYuanKuServiceImpl extends BaseServiceImpl<ChuanYuanKuMapper, ChuanYuanKuDO>
        implements ChuanYuanKuService {

    @Resource
    private ISystemUserService systemUserService;

    /**
     * 查询船员分页列表
     */
    @Override
    public  List<ChuanYuanKuVO> findChuanYuanKuBiao(){
        LambdaQueryWrapper<ChuanYuanKuDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(ChuanYuanKuDO::getCreateTime);
        return tranferListBo(this.list(lambdaQueryWrapper),ChuanYuanKuVO.class);
    }

    /**
     * 查询船员分组分页列表
     */
    @Override
    public Page<ChuanYuanKuVO> findChuanYuanKuGroup(ChuanYuanKuSearchPO searchPO) {
        LambdaQueryWrapper<ChuanYuanKuDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(searchPO.getXingMing()), ChuanYuanKuDO::getXingMing, searchPO.getXingMing());
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(searchPO.getShenFenHao()), ChuanYuanKuDO::getShenFenHao, searchPO.getShenFenHao());
        lambdaQueryWrapper.eq(Objects.nonNull(searchPO.getFenZuId()), ChuanYuanKuDO::getFenZuId, searchPO.getFenZuId());
        lambdaQueryWrapper.orderByDesc(ChuanYuanKuDO::getCreateTime);
        Page<ChuanYuanKuDO> page = new Page<>(searchPO.getPageNo(), searchPO.getPageSize());
        Page<ChuanYuanKuDO> page1 = this.page(page, lambdaQueryWrapper);
        return tranferPageBo(page1, ChuanYuanKuVO.class);
    }


    /**
     * 查询船员分页列表
     */
    @Override
    public Page<ChuanYuanKuVO> findChuanYuanKu(ChuanYuanKuSearchPO searchPO) {
        LambdaQueryWrapper<ChuanYuanKuDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //lambdaQueryWrapper.like(StringUtils.isNotEmpty(searchPO.getShenFenHao()), ChuanYuanKuDO::getShenFenHao, searchPO.getShenFenHao());
        //lambdaQueryWrapper.like(StringUtils.isNotEmpty(searchPO.getXingMing()), ChuanYuanKuDO::getXingMing, searchPO.getXingMing());
        if(StringUtils.isNotEmpty(searchPO.getXingMing())){
            lambdaQueryWrapper.and(w->{
                w.like(ChuanYuanKuDO::getXingMing,searchPO.getXingMing())
                .or()
                .like(ChuanYuanKuDO::getShenFenHao,searchPO.getXingMing());
            });
        }

        lambdaQueryWrapper.eq(Objects.nonNull(searchPO.getFenZuId()), ChuanYuanKuDO::getFenZuId, searchPO.getFenZuId());
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(searchPO.getZhiWei()), ChuanYuanKuDO::getZhiWei, searchPO.getZhiWei());
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(searchPO.getZhengShuDengJi()), ChuanYuanKuDO::getZhengShuDengJi, searchPO.getZhengShuDengJi());

        // 查询用户分组
        SysUserDetailVO sysUserDetailVO = systemUserService.selectById(UserThreadLocal.get().getId());
        String groupIds = sysUserDetailVO.getGroupIds();
        if (StringUtils.isNotEmpty(groupIds)) {
            List<Long> collect = Arrays.stream(groupIds.split(",")).toList().stream().map(Long::parseLong).collect(Collectors.toList());
            //lambdaQueryWrapper.in(ChuanYuanKuDO::getFenZuId, collect);
            lambdaQueryWrapper.and(w->{
                w.in(ChuanYuanKuDO::getFenZuId,collect)
                        .or()
                        .isNull(ChuanYuanKuDO::getFenZuId);
            });
        } else {
            lambdaQueryWrapper.isNull(ChuanYuanKuDO::getFenZuId);
        }

        lambdaQueryWrapper.orderByDesc(ChuanYuanKuDO::getCreateTime);
        Page<ChuanYuanKuDO> page = new Page<>(searchPO.getPageNo(), searchPO.getPageSize());
        Page<ChuanYuanKuDO> page1 = this.page(page, lambdaQueryWrapper);
        return tranferPageBo(page1, ChuanYuanKuVO.class);
    }


    /**
     * 保存
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ChuanYuanKuVO saveChuanYuanKu(ChuanYuanKuSavePO savePO) {
        savePO.setId(null); //新增不需要id

        ChuanYuanKuDO chuanYuanKuDOByDB = this.lambdaQuery()
                .eq(ChuanYuanKuDO::getShenFenHao, savePO.getShenFenHao())
                .one();
        if (chuanYuanKuDOByDB != null) {
            throw new RuntimeException("该身份证号已存在，请联系管理员");
        }

        ChuanYuanKuDO chuanBoZhiWeiDO = tranferBo(savePO, ChuanYuanKuDO.class);
        if (Objects.nonNull(chuanBoZhiWeiDO)) {
            if(Objects.nonNull(savePO.getSystemId())){
                chuanBoZhiWeiDO.setSystemId(savePO.getSystemId());
                chuanBoZhiWeiDO.setSystemName("");
            }else {
                chuanBoZhiWeiDO.setSystemId(UserThreadLocal.get().getSystemId());
                chuanBoZhiWeiDO.setSystemName(UserThreadLocal.get().getSystemName());
            }
            this.saveOrUpdate(chuanBoZhiWeiDO);
            return tranferBo(chuanBoZhiWeiDO, ChuanYuanKuVO.class);
        }
        return null;
    }

    /**
     * 修改
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ChuanYuanKuVO updateChuanYuanKu(ChuanYuanKuSavePO savePO) {
        if (savePO.getId() == null) {
            throw new RuntimeException("id不能为空");
        }
        ChuanYuanKuDO chuanYuanKuDOByDB = this.lambdaQuery()
                .eq(ChuanYuanKuDO::getShenFenHao, savePO.getShenFenHao())
                .ne(ChuanYuanKuDO::getId, savePO.getId())
                .one();
        if (chuanYuanKuDOByDB != null) {
            throw new RuntimeException("该身份证号已存在，请联系管理员");
        }

        ChuanYuanKuDO chuanBoZhiWeiDO = tranferBo(savePO, ChuanYuanKuDO.class);
        if (Objects.nonNull(chuanBoZhiWeiDO)) {
            this.updateById(chuanBoZhiWeiDO);
            return tranferBo(chuanBoZhiWeiDO, ChuanYuanKuVO.class);
        }
        return null;
    }


    /**
     * 删除
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delChuanYuanKu(Long id) {
        return this.removeById(id);
    }


    /**
     * 船员状态修改。
     * 0:停用、1:启用
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateStatus(StatusRequest statusRequest) {
        if (ValidatorUtil.isNumeric(statusRequest.getValue())) {
            return this.updateStatus(statusRequest.getId(), statusRequest.getField(), Integer.parseInt(statusRequest.getValue()));
        } else {
            return this.updateStatusStr(statusRequest.getId(), statusRequest.getField(), statusRequest.getValue());
        }
    }


    @Override
    public ChuanYuanKuVO getChuanYuanKu(Long id) {
        ChuanYuanKuDO chuanBoZhiWeiDO = getById(id);
        return tranferBo(chuanBoZhiWeiDO, ChuanYuanKuVO.class);
   }

    @Override
    public ChuanYuanKuVO getChuanYuanKuByOpenid(String openid) {
        LambdaQueryWrapper<ChuanYuanKuDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ChuanYuanKuDO::getOpenid,openid);
        ChuanYuanKuDO chuanBoZhiWeiDO = getOne(lambdaQueryWrapper);
        return tranferBo(chuanBoZhiWeiDO, ChuanYuanKuVO.class);
    }
}
